/**平台管理首页
 * @author wangze
 * @date 2017-12-14 13:35.
 **/

(function () {

    var _bt = window.BT,
        _util = _bt.util,
        _debug = _util.debug,
        _dialog = _util.dialog,
        _config = _util.config,
        _enum = _config.enumValues,
        _platStatusEnum = _enum.platStatus,
        _platTypeEnum = _enum.platType,
        _url = _config.url,
        _sUrl = _url.select,
        _pUrl = _url.platform;


    var gridOpt = {
        url: _pUrl.list,
        formatters: {
            'platStatusFormat': function (column, row) {
                var r = _enum.getSelected(_enum.platStatus, row.status);
                if (!(r && r.name)) {
                    return '';
                }
                switch (row.status) {
                    case _enum.platStatus.forbidden.value:
                        return '<span class="label label-danger height-auto">' + r.name + '</span>';
                    case _enum.platStatus.start.value:
                        return '<span class="label label-success height-auto">' + r.name + '</span>';
                    case  _enum.platStatus.trial.value:
                        return '<span class="label label-primary height-auto">' + r.name + '</span>';
                    default:
                        return '';
                }
            },
            'platTypeFormat': function (column, row) {
                var r = _enum.getSelected(_platTypeEnum, row.type);
                if (!(r && r.name)) {
                    return '';
                }
                return r.name;

            },
            'areaFormat': function (column, row) {
                var r;
                var trim = function (v) {
                    if (v) {
                        return v + '-';
                    } else {
                        return '';
                    }
                };
                //直辖市去重
                if (row.province === row.city) {
                    row.province = '';
                }
                r = trim(row.province) + trim(row.city) + trim(row.area);
                if (r) {
                    return r.substr(0, r.length - 1);
                } else {
                    return '';
                }
            },
            'timeFormat': function (column, row) {
                if (!row.startdate) {
                    return '';
                }
                var date = new Date(row.startdate);
                return date.Format('yyyy-MM-dd');
            },
            'commands': function (column, row) {
                // var result = '<button class="btn btn-xs btn-purple command-edit" data-row-id="' + row.id + '">平台管理</button>';
                //
                // if (row.type === _platTypeEnum.garden.value) {
                //     result += '<button class="btn btn-xs btn-purple obligee-list-view" data-row-id="' + row.id + '" style="margin-left: 10px;">权利人管理</button>'
                // }
                var commands = [];

                commands.push('<button class="btn btn-xs btn-red command-update" style="width:60%;" data-row-id="' + row.id + '">平台报表更新</button>');
                commands.push('<button class="btn btn-xs btn-purple command-edit" style="width:40%;" data-row-id="' + row.id + '" style="margin-left: 10px;">平台管理</button>');

                return commands.join('');
            }
        }
    };
    var page = {
        grid: null,
        init: function () {
            page.initPage();
            page.edit.addValidateRule();
            page.grid = new _bt.BGrid(gridOpt);
            page.bind();
        }
    };

    page.common = {
        /**
         * select 公共方法
         * @param ele
         * @param data
         * @param _emptyText
         */
        selectInit: function (ele, data, _emptyText) {
            var html = [_emptyText];
            $.each(data, function (i, item) {
                html.push('<option value="' + item.value + '">' + item.name + '</option>');
            });
            ele.html(html.join(''));
        },
        /**
         * 获取栏目样式
         */
        roleInit: function (ele, _emptyText, isAsync) {
            var successEvent = function (data) {
                if (data && data.flag) {
                    data = data.data;
                    if (data && data.length) {
                        var html = [_emptyText];
                        $.each(data, function (i, item) {
                            html.push('<option value="' + item.id + '">' + item.name + '</option>');
                        });
                        ele.html(html.join(''));
                    }
                } else {
                    _debug.info(data);
                }
            };
            _util.ajax({
                url: _pUrl.column,
                type: 'get',
                async: !(isAsync === false)
            }, successEvent);

        },
        /**
         * 一些公共的初始化
         * @param form
         * @param emptyText
         * @param emptyAllText
         * @param isAsync 是否异步
         */
        init: function (form, emptyText, emptyAllText, isAsync) {
            page.common.roleInit($('[name=rolesid]', form), emptyText, isAsync);
            //获取所有的状态
            page.common.selectInit($('[name=status]', form), _enum.getArray(_enum.platStatus), emptyAllText);
            //获取所有平台的类型
            page.common.selectInit($('[name=type]', form), _enum.getArray(_enum.platType), emptyText);
        }

    };
    /**
     * 公共数据的初始化
     */
    page.initPage = function () {
        var emptyText = '<option value="">-请选择-</option>',
            allText = '全部',
            emptyAllText = '<option value="">' + allText + '</option>',
            $formSearch = $('#form-search');
        /**
         * 省市区
         */
        $('#search-area', $formSearch).city({
            provinceUrl: _sUrl.province,
            cityUrl: _sUrl.city,
            areaUrl: _sUrl.area,
            emptyText: allText,
            ajaxSetting: {
                error: _util.ajaxError()
            }
        });
        page.common.init($formSearch, emptyText, emptyAllText);
    };

    /**
     *编辑页面初始化
     */
    page.edit = {
        form: '#form-edit',
        dialog: null,
        addValidateRule: function () {
            /**
             * 平台唯一
             */
            $.validator.addMethod("nameUnique", function (value, element) {

                var isSuccess = false;
                var successEvent = function (data) {
                    if (data && data.flag) {
                        isSuccess = true;
                    } else {
                        // _dialog.info('验证用户名重复失败');
                    }
                };
                //编辑的时候，如果用户名不变，则不校验用户名重复
                var originName = $(element).attr('data-origin-name');
                if (originName && value === originName) {
                    return this.optional(element) || true;
                }

                _util.ajax({
                    url: _pUrl.check,
                    type: 'get',
                    async: false,
                    data: {platformName: value}
                }, successEvent);
                return this.optional(element) || isSuccess;

            }, "名称重复");
        },
        addValidate: function (form) {
            var validateOpt = {
                ignore: ':hidden',
                rules: {
                    type: {required: true},
                    name: {required: true, nameUnique: true},
                    rolesid: {required: true},
                    type: {required: true},
                    // province: {required: true},
                    // city: {required: true},
                    // area: {required: true},
                    status: {required: true}
                },
                messages: {
                    type: {required: '必填'},
                    name: {required: '必填'},
                    rolesid: {required: '必填'},
                    type: {required: '必填'},
                    // province: {required: '必填'},
                    // city: {required: '必填'},
                    // area: {required: '必填'},
                    status: {required: '必填'}
                },
                submitHandler: function (form) {
                    var successEvent = function (data) {
                        if (data && data.flag) {
                            _dialog.info('保存成功');
                            page.edit.hide();
                            page.grid.reload();
                        } else {
                            _dialog.warn('保存失败');
                        }
                    };
                    _util.jsonAjax({
                        url: _pUrl.save,
                        type: 'post',
                        data: $(form).serializeObject()
                    }, successEvent);
                }
            };
            var selectArea = $('#edit-area', form);
            var changeEvent = function () {
                var selectedTypeValue = $(this).val();
                if (!selectedTypeValue) {
                    return;
                }
                selectedTypeValue = parseInt(selectedTypeValue, 10);
                selectArea.children('select:eq(0)').val('').trigger('change');
                switch (selectedTypeValue) {
                    case _platTypeEnum.province.value:
                        selectArea.children('select:eq(0)').show().siblings('select').hide();
                        //form.valid();
                        break;
                    case _platTypeEnum.city.value:
                        selectArea.children('select:eq(2)').hide().siblings('select').show();
                        //form.valid();
                        break;
                    case _platTypeEnum.area.value:
                    case _platTypeEnum.garden.value:
                        selectArea.children('select').show();
                        //form.valid();
                        break;
                    default:
                        _dialog.info('页面出错了');
                        break;
                }
            };
            //添加select 验证
            $('[name=type]', form).on('change', changeEvent);

            return form.validate($.extend({}, _util.validate.default, validateOpt));
        },
        loadData: function (id) {
            var $form = $(page.edit.form);
            var _text = '-请选择-';
            var emptyText = '<option value="">' + _text + '</option>';

            var $editArea = $('#edit-area', $form);
            var placeInit = function (p, c, a) {
                // $editArea.city({
                //     provinceUrl: _sUrl.province,
                //     cityUrl: _sUrl.city,
                //     areaUrl: _sUrl.area,
                //     emptyText: _text,
                //     province: p,
                //     city: c,
                //     area: a
                // });
                $editArea.city({
                    dataType: 'json',
                    valueType: 'name',
                    province: p,
                    city: c,
                    area: a,
                    nodata: ''
                });
            };

            var editSuccessEvent = function (data) {
                if (!(data && data.flag)) {
                    _debug.log(data);
                    return;
                }
                data = data.data;
                if (!data) {
                    _debug.log('没有获取到数据');
                    return;
                }
                data.id = id;
                $form.bindForm(data);
                page.edit.addValidate($form);
                //触发省市区选择相关规则
                //修改的时候，不能修改平台类型和所属区域
                $('[name=type]', $form).trigger('change').prop('disabled', true);
                $('[name="name"]').attr('data-origin-name', data.name);//编辑的时候，验证是否是原平台名
                placeInit(data.province || '', data.city || '', data.area || '');
                $editArea.children('select').prop('disabled', true);
            };

            page.common.init($form, emptyText, emptyText, false);
            /**
             * 修改
             */
            if (id) {
                _util.ajax({
                    url: _pUrl.edit,
                    type: 'get',
                    data: {id: id}
                }, editSuccessEvent);
            }
            /**
             * 新增，要获取菜单menu
             */
            else {
                page.edit.addValidate($form);
                placeInit();
            }


        },
        show: function (title, id) {
            var m = _dialog.edit({
                message: $('#edit-template').html(),
                title: title
            }, {
                init: function () {
                    page.edit.loadData(id);
                },
                success: function () {
                    $('#form-edit').submit();
                    return false;
                }
            });
            page.edit.dialog = m;
            return m;
        },
        hide: function () {
            page.edit.dialog && page.edit.dialog.modal('hide');
        }
    };


    page.bind = function () {
        var showDialog = page.edit.show;
        var searchEvent = function () {
            //TODO 添加查询参数
            page.grid.reload();
        };
        var addEvent = function () {
            showDialog('新增平台');
        };

        var delEvent = function () {
            //选择数据
            var ids = page.grid.getSelections();
            if (ids.length === 0) {
                _dialog.warn('请选择一条数据');
                return;
            }
            _dialog.confirm('确定删除吗?', function () {
                _util.ajax({
                    type: 'get',
                    url: _pUrl.del,
                    data: {idStr: ids.join(',')}
                }, function (data) {
                    if (data && data.flag) {
                        _dialog.info('删除成功');
                        page.grid.reload();
                    } else {
                        _dialog.warn('删除失败');
                    }
                });
            });


        };
        $('#btn-search').on('click', searchEvent);
        $('#btn-add').on('click', addEvent);
        $('#btn-del').on('click', delEvent);

        /**
         * 绑定grid上的编辑事件
         */
        page.grid.on('loaded', function () {

            $('.command-edit').on('click', function () {
                var id = $(this).attr('data-row-id');
                page.edit.show('平台管理', id);
                return false;
            });

            // $('.obligee-list-view').on('click', function () {
            //     var id = $(this).attr('data-row-id');
            //     $('#my-obligee-Modal').modal('show');
            // });


            $('.command-update').on('click', function () {
                var id = $(this).attr('data-row-id');
                _util.ajax({
                    url: _pUrl.updateReport,
                    data: {platformId: id}
                }, function (data) {
                    if (data && data.code === 0) {
                        var layerIndex = _dialog.infoNoBtn('开始更新报表，请稍等....');
                        updateRemote(id, layerIndex);
                    } else {
                        if (data.code === 420) {
                            _dialog.warn('请配置区域');
                            return;
                        }
                        else if (data.code === 421) {
                            _dialog.warn('请配置今年指标');
                            return;
                        } else {
                            _dialog.warn('其他错误');
                        }
                    }
                });
            });

            /**
             * 调用更新报表后台接口
             * @param platformId
             */
            function updateRemote(platformId, layerIndex) {
                _util.ajax({
                    type: 'get',
                    url: _config.updateReportUrl,
                    data: {webPlatformId: platformId}
                }, function (data) {
                    if (data && data.code === 0) {
                        _dialog.close(layerIndex);
                        _dialog.info('平台报表更新完成');
                    } else {
                        _dialog.warn(data.msg);
                    }

                });

            }
        });


    };

    $(function () {
        page.init();
    });

})();